package com.nwpu.hass.utils;

import antlr.Token;
import com.nwpu.hass.domain.Auth4Wechat;
import com.nwpu.hass.domain.TokenBody;
import com.nwpu.hass.exceptions.AuthorizeWechatException;
import com.nwpu.hass.utils.faceutils.GsonUtils;
import com.nwpu.hass.utils.faceutils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author alecHe
 * @desc ...
 * @date 2021-01-09 20:56:30
 */
@Slf4j
@Component
public class EmailSender {

    @Value("${spring.mail.username}")
    private String senderEmail;
    @Autowired
    private JavaMailSenderImpl mailSender;

    @Async
    public void sendTxtMail(String receiverEmail,String deviceIds) {

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        //设置接收邮箱
        simpleMailMessage.setTo(new String[]{receiverEmail});

        //设置发送邮箱
        simpleMailMessage.setFrom(senderEmail);

        simpleMailMessage.setSubject("设备报修预警-" + deviceIds);

        simpleMailMessage.setText("经过HASS内部计算系统计算和评估，警告设备ID为" + deviceIds
                + "存在需报修/报废的风险。请仓库管理员前往仓库查看。\n" +
                "祝好\n" +
                new Date());

        mailSender.send(simpleMailMessage);

        log.info("邮件已发送至 " + receiverEmail);
    }

    @Async
    public void sendWechatMail(String wechatAccount,String deviceIds) throws Exception {

        String res = HttpUtil.getAccessToken();

        TokenBody info = GsonUtils.fromJson(res,TokenBody.class);
        String accessToken = info.getAccess_token();

        if(null == accessToken){
            throw new AuthorizeWechatException("微信accessToken获取失败");
        }

        HttpUtil.sendSubscribe(accessToken,wechatAccount,deviceIds);

        log.info("微信弹窗通知已发送至，微信openID为 " + wechatAccount);
    }

}
